{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.models import load_model\n",
    "from collections import deque\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import argparse\n",
    "import pickle\n",
    "import cv2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "args = {\n",
    "\t\n",
    "\t\"model\": \"model/violence_resnet50.h5\",\n",
    "    \"label-bin\": \"model/lb.pickle\",\n",
    "    \"input\": \"video/street-fight.mp4\",\n",
    "    \"output\": \"output/streetfight_64avg.avi\",\n",
    "    \"size\": 64\n",
    "    \n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[INFO] loading model and label binarizer...\n"
     ]
    }
   ],
   "source": [
    "# load the trained model and label binarizer from disk\n",
    "print(\"[INFO] loading model and label binarizer...\")\n",
    "model = load_model(args[\"model\"])\n",
    "lb = pickle.loads(open(args[\"label-bin\"], \"rb\").read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the image mean for mean subtraction along with the\n",
    "# predictions queue\n",
    "mean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\n",
    "Q = deque(maxlen=args[\"size\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the video stream, pointer to output video file, and\n",
    "# frame dimensions\n",
    "vpath = args[\"input\"]\n",
    "if args[\"input\"] == 'camera':\n",
    "\tvpath = 0\n",
    "vs = cv2.VideoCapture(vpath)\n",
    "writer = None\n",
    "(W, H) = (None, None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[INFO] cleaning up...\n"
     ]
    }
   ],
   "source": [
    "# loop over frames from the video file stream\n",
    "while True:\n",
    "\t# read the next frame from the file\n",
    "\t(grabbed, frame) = vs.read()\n",
    "\n",
    "\t# if the frame was not grabbed, then we have reached the end\n",
    "\t# of the stream\n",
    "\tif not grabbed:\n",
    "\t\tbreak\n",
    "\n",
    "\t# if the frame dimensions are empty, grab them\n",
    "\tif W is None or H is None:\n",
    "\t\t(H, W) = frame.shape[:2]\n",
    "\n",
    "\t# clone the output frame, then convert it from BGR to RGB\n",
    "\t# ordering, resize the frame to a fixed 224x224, and then\n",
    "\t# perform mean subtraction\n",
    "\toutput = frame.copy()\n",
    "\tframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "\tframe = cv2.resize(frame, (224, 224)).astype(\"float32\")\n",
    "\tframe -= mean\n",
    "\n",
    "\t# make predictions on the frame and then update the predictions\n",
    "\t# queue\n",
    "\tpreds = model.predict(np.expand_dims(frame, axis=0))[0]\n",
    "\tQ.append(preds)\n",
    "\n",
    "\t# perform prediction averaging over the current history of\n",
    "\t# previous predictions\n",
    "\tresults = np.array(Q).mean(axis=0)\n",
    "\t# i = np.argmax(results)\n",
    "\ti = 1\n",
    "\tlabel = lb.classes_[i]\n",
    "\t\n",
    "\n",
    "\t# draw the activity on the output frame\n",
    "\t# prob = model.predict_proba(np.expand_dims(frame, axis=0))[0] # to show probability of frame\n",
    "\tprob = results[i]*100\n",
    "\n",
    "\ttext_color = (0, 255, 0) # default : green\n",
    "\n",
    "\tif prob > 70 : # Violence prob\n",
    "\t\ttext_color = (0, 0, 255) # red\n",
    "\t\n",
    "\telse:\n",
    "\t\tlabel = 'Normal'\n",
    "\n",
    "\ttext = \"State : {:8} ({:3.2f}%)\".format(label,prob)\n",
    "\tFONT = cv2.FONT_HERSHEY_SIMPLEX \n",
    "\n",
    "\tcv2.putText(output, text, (35, 50), FONT,1.25, text_color, 3) \n",
    "\n",
    "\t# plot graph over background image\n",
    "\toutput = cv2.rectangle(output, (35, 80), (35+int(prob)*5,80+20), text_color,-1)\n",
    "\n",
    "\t# check if the video writer is None\n",
    "\tif writer is None:\n",
    "\t\t# initialize our video writer\n",
    "\t\tfourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n",
    "\t\twriter = cv2.VideoWriter(args[\"output\"], fourcc, 30,(W, H), True)\n",
    "\n",
    "\t# write the output frame to disk\n",
    "\twriter.write(output)\n",
    "\n",
    "\t# show the output image\n",
    "\tcv2.imshow(\"Output\", output)\n",
    "\tkey = cv2.waitKey(1) & 0xFF\n",
    "\n",
    "\t# if the `q` key was pressed, break from the loop\n",
    "\tif key == ord(\"q\"):\n",
    "\t\tbreak\n",
    "# release the file pointersq\n",
    "print(\"[INFO] cleaning up...\")\n",
    "writer.release()\n",
    "vs.release()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
